extern "C"
{
  #include "lib/printf/printf_port.c"
}

extern "C"
{
  #include "lib\nrf24\nrf24_port.c"
  #include "lib\nrf24\nrf24_device.c"
  #include "lib\nrf24\nrf24_main.c"
}
void prx_all_clear()
{//清FIFO 清IRQ 拉低CE防止触发TX
  nrf_tx_flush();
  nrf_rx_flush();
  nrf_clear_irq_src(0x07);
}
void prx_init()
{
  delay(150);
  PRINT("\r\ninit PRX.... status: 0x%02X\r\n", nrf_status());
  char adr_msb_first[5] = {0x5A, 0x5A, 0x5A, 0x5A, 0x5A};
  nrf_power_up();
  nrf_set_primary_mode(1); //PRX
	nrf_set_rf_channel(2500);
	nrf_set_rf_data_rate(NRF_VAL_RF_DR_2Mbps);
  nrf_set_addr_wid(NRF_VAL_AW_5Bytes);
	nrf_set_pipe_addr(NRF_PIPE0, adr_msb_first, 5);
	nrf_set_tx_addr(adr_msb_first, 5);
	nrf_pipe_enable(NRF_PIPE0);
  prx_all_clear();
}
// the setup routine runs once when you press reset:
void setup() {
  log_init();
  NRF_SPI_INIT();
  prx_init();
  NRF_CE_HIGH();
  delay(5);
  PRINT("----setup() finished for PRX----");
}
void rx_process()
{
  static char rxbuf[33] = {0,};
  static char txbuf[33] = {0,};
  //以最快速度，读取-处理-回复ACK payload
  char sz = nrf_rx_payload_wid();
  if(sz>0) {
    nrf_rx_read_payload(rxbuf, sz);
    for(char i=0; i<sz; i++) {
      txbuf[i] = rxbuf[sz-1-i];
    }
    nrf_ack_write_payload(NRF_PIPE0, txbuf, sz);
    //忙完之后再打印log
    rxbuf[sz] = 0;
    txbuf[sz] = 0;
    PRINT("get data from PTX: %s\r\n", rxbuf);
    PRINT("PRX ACK payload: %s\r\n", txbuf);
    delay(20);//等一会儿再清理FIFO
    PRINT("-over-\r\n");
  } else {
    PRINT("bad rx payload length: 0x%02X\r\n", sz);
  }
}
// the loop routine runs over and over again forever:
void loop() {
  PRINT("\r\nstart listening......\r\n");
  while(NRF_IRQ_PIN());
  char status = nrf_status();
  if(NRF_STATUS_RXDR(status)) {
    rx_process();
  } else {
    PRINT("bad status: 0x%02X\r\n", status);
  }
  prx_all_clear();
}
